f.measure <- function(target, prediction) {
  classes <- sort(unique(target))
  nData <- length(target)
  fMeasure <- 0
  
  for(i in classes) {
    n <- sum(target==i)                                                         #number of elements of class i
    tp <- sum((target==i) & (prediction==i))                                    #number of true positifs
    fp <- sum((target!=i) & (prediction==i))                                    #number of false positifs
    fn <- sum((target==i) & (prediction!=i))                                    #number of false negatives
    precision <- tp / (tp + fp)                                                 #precision
    recall <- tp / (tp + fn)                                                    #recall
    temp <- 2 * (n/nData) * ((precision * recall) / (precision + recall))       #F1-Score formula (weighted)
    if (!is.nan(temp)) {
      fMeasure <- fMeasure + temp
    }
  }
  fMeasure
}